import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,clearAll } from '@/utils/myAuth'
import router from "@/router/index"
// create an axios instance
const service = axios.create({
//   baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  
  timeout: 5000 
})

// request interceptor
service.interceptors.request.use(
  config => {
    var token=getToken()
    if(token){
        config.headers['token']=getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  
  response => {
    const res = response.data
    if(res.code===20002){
        clearAll()//清空用户信息
         router.push('/login') //跳转登录页面
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service